﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using System.Threading;

using Commander.Classes;
using Commander.Structures;

namespace Commander.Views
{
    /// <summary>
    /// Логика взаимодействия для Copy.xaml
    /// </summary>
    public partial class Copy : Window
    {
        private Thread cop;
        public delegate void copClose();
        private int Count;
        private int val;
        private Point old;

        private Info data;

        public Copy()
        {
            InitializeComponent();
        }

        public Copy(Info Data)
        {
            InitializeComponent();
            data = Data;
            Count = Work.CountFile(data);
            progressBar2.Minimum = 0;
            progressBar2.Maximum = Count;
            progressBar2.Value = val = 0;
        }

        public bool DeleteFile(string FileName)
        {            
            try
            {
                if (!File.Exists(FileName)) return true;
                FileInfo f = new FileInfo(FileName);
                f.IsReadOnly = false;                
                f.Delete();
            }
            catch(Exception error) 
            {
                MessageBox.Show(error.ToString());
            }

            return !File.Exists(FileName);
        }

        public bool DeleteDir(string FolderName)
        {
            if (!Directory.Exists(FolderName))
            {
                return true;
            }
            
            foreach (string files in Directory.GetFiles(FolderName))
            {
                DeleteFile(files);
            }

            foreach (string folder in Directory.GetDirectories(FolderName))
            {
                DeleteDir(folder);
            }
            
            try
            {                
                Directory.Delete(FolderName);
            }
            catch(Exception error)
            {
                MessageBox.Show(error.ToString());
            }
            return !Directory.Exists(FolderName);
        }

        /// <summary>
        /// Копирование файла
        /// </summary>
        /// <param name="oldName"></param>
        /// <param name="newName"></param>
        /// <returns></returns>
        public bool CopyFile(string oldName, string newName)
        {
            if (!Directory.Exists(System.IO.Path.GetDirectoryName(newName)))
            {
                try
                {
                    this.Dispatcher.BeginInvoke((Action)(() => 
                    { 
                        this.label2.Content = oldName; 
                        this.label4.Content = newName;
                        progressBar2.Value = ++val;
                        label6.Content = (int)val * 100 / Count + "%";
                    }));
                    Directory.CreateDirectory(System.IO.Path.GetDirectoryName(newName));
                }
                catch
                { 
                    return false;
                }
            }

            if (File.Exists(newName))
            {
                MessageBoxResult result = MessageBox.Show("Файл " + newName + " уже иснуэ, перезаписать его ?", "Удалить", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    File.Delete(newName);
                }
                else
                {
                    //добавить логику
                }
            }
            try
            {
                this.Dispatcher.BeginInvoke((Action)(() => 
                { 
                    this.label2.Content = oldName; 
                    this.label4.Content = newName;
                    progressBar2.Value = ++val;
                    this.label6.Content = (int)val * 100 / Count + " %";
                }));
                File.Copy(oldName, newName);
            }
            catch
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// Копирование папки
        /// </summary>
        /// <param name="oldName"></param>
        /// <param name="newName"></param>
        public void CopyDir(string oldName, string newName)
        {
            if (Directory.Exists(newName))
            {
                MessageBoxResult result = MessageBox.Show("Директория " + newName + " уже сучествует, перезаписать ее?", "Удаление", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    DeleteDir(newName);
                }
                else
                {
                    //добавить логику
                }
            }
            Directory.CreateDirectory(newName); 

            if (data.Type != "")
            {
                foreach (string files in Directory.GetFiles(oldName,data.Type))
                {
                    CopyFile(files, newName + "\\" + System.IO.Path.GetFileName(files));
                }
            }
            else
            {
                foreach (string files in Directory.GetFiles(oldName))
                {
                    CopyFile(files, newName + "\\" + System.IO.Path.GetFileName(files));
                }
            }

            foreach (string folder in Directory.GetDirectories(oldName))
            {
                CopyDir(folder, newName + "\\" + System.IO.Path.GetFileName(folder));
            }
        }

        public void clos()
        {
            this.Close();
        }

        private void Copi()
        {
            string tmp=data.OldPatch;
            foreach (IOView item in data.files)
            {
                if (item.Size == "<Папка>")
                {
                    if (item.Name != "..")
                    {
                        tmp += item.Name + @"\";
                        CopyDir(data.OldPatch + item.Name, data.NewPatch + item.Name);
                    }
                }
                else
                {
                    tmp += item.Name + "." + item.Type;
                    CopyFile(data.OldPatch + item.Name + "." + item.Type, data.NewPatch + item.Name + "." + item.Type);
                }
            }
            this.Dispatcher.BeginInvoke(new copClose(clos), System.Windows.Threading.DispatcherPriority.Background);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            cop = new Thread(new ThreadStart(Copi));
            cop.Start();
        }

        private void Window_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            old = e.GetPosition(null); 
        }

        private void Window_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                Point cur = e.GetPosition(null);
                this.Left += cur.X - old.X;
                this.Top += cur.Y - old.Y;
            }
        }
    }
}
